import org.junit.jupiter.api.Test;

/*
 * @description 懒汉式（线程安全）
 * @author 罗添煦
 * @create 2024-08-20 下午3:35
 */
public class Singleton_02 {

    public static Singleton_02 instance;

    private Singleton_02() {}

    /**
     * 获取唯一实例
     * @return 实例
     */
    public static synchronized Singleton_02 getInstance() {
        if (instance == null) {
            instance = new Singleton_02();
        }
        return instance;
    }

    /**
     * 测试是否是单例对象
     */
    @Test
    public void test1() {
        Singleton_02 instance1 = Singleton_02.getInstance();
        Singleton_02 instance2 = Singleton_02.getInstance();
        System.out.println(instance1 == instance2);
    }

    /**
     * 测试多线程，导致线程不安全问题
     */
    @Test
    public void test2() {
        Thread thread1 = new Thread(()->{
            Singleton_02 instance1 = Singleton_02.getInstance();
            System.out.println(instance1);
        });
        Thread thread2 = new Thread(()->{
            Singleton_02 instance2 = Singleton_02.getInstance();
            System.out.println(instance2);
        });
        thread1.start();
        thread2.start();
    }
}
